package cn.yzj.utils;

import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * Gzip 压缩解压工具类
 *
 * @author gzkemays
 * @since 2021/12/21 14:32
 */
public class GzipUtils {
  /**
   * gzip 压缩
   *
   * @param str 源文本
   * @return 压缩数据
   */
  public static String compress(String str) {
    if (!StringUtils.hasText(str)) {
      return str;
    }
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    GZIPOutputStream gzip = null;
    try {
      gzip = new GZIPOutputStream(bos);
      gzip.write(str.getBytes(StandardCharsets.UTF_8));
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (gzip != null) {
        try {
          gzip.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return Base64Utils.encodeToString(bos.toByteArray());
  }

  /**
   * gzip 解压
   *
   * @param str 压缩数据
   * @return 源文本
   */
  public static String uncompress(String str) {
    if (!StringUtils.hasText(str)) {
      return str;
    }
    byte[] decode = Base64Utils.decodeFromString(str);
    ByteArrayInputStream bais = new ByteArrayInputStream(decode);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
      GZIPInputStream gzip = new GZIPInputStream(bais);
      byte[] buffer = new byte[1024];
      int i;
      while ((i = gzip.read(buffer)) != -1) {
        baos.write(buffer, 0, i);
      }
      gzip.close();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        bais.close();
        baos.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    try {
      return URLDecoder.decode(baos.toString(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return baos.toString();
  }

  public static void main(String[] args) {
    String uncompress =
        uncompress(
            "H4sIAAAAAAAAA02MMRLAIAgEX7O9UaNQYkL+/6SgNs5cwSx7Ry7khN/IzSh4ZRjieEMEvfCOBqnrJciW4+gkY9b3QseemVOziunUIpO/WHDBPkY9lhu6YFQ0of0HWUNOE5YAAAA=");
    System.out.println(uncompress);
    try {
      System.out.println(URLDecoder.decode(uncompress, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
  }
}
